package com.haopt.clock.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.haopt.clock.dao.*;
import com.haopt.clock.dto.ResultDTO;
import com.haopt.clock.entity.*;
import com.haopt.clock.po.ClockInListPO;
import com.haopt.clock.service.ClockInService;
import com.haopt.clock.utils.BeanHelper;
import com.haopt.clock.utils.DataUtil;
import com.haopt.clock.utils.IdBuilderUtil;
import com.haopt.clock.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.xml.transform.Source;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

@Service
public class ClockInServiceImpl implements ClockInService {

    @Autowired
    private TClockInMapper clockInMapper;
    @Autowired
    private TUserMapper userMapper;
    @Autowired
    private TClassificationMapper classificationMapper;
    @Autowired
    private TIntegralMapper integralMapper;
    @Autowired
    private TRecordMapper recordMapper;


    @Transactional
    @Override
    public ResultDTO<ResIdVO> add(ReqClockInAddVO reqVo) {
        if(DataUtil.isNullOrEmpty(reqVo.getUserId()) || DataUtil.isNullOrEmpty(reqVo.getClassificationId())){
            return ResultDTO.errorOf(3001, "当前网络繁忙，请重新打卡");
        }
        //数据完整性检验
        TUser user = userMapper.selectByPrimaryKey(reqVo.getUserId());
        if(DataUtil.isNullOrEmpty(user)){
            return ResultDTO.errorOf(3002, "当前网络繁忙，请重新打卡");
        }
        //添加打卡记录
        TClockIn tClockIn = BeanHelper.copyProperties(reqVo, TClockIn.class);
        tClockIn.setId(IdBuilderUtil.getId());
        tClockIn.setCreateTime(System.currentTimeMillis());
        tClockIn.setUpdateTime(System.currentTimeMillis());
        tClockIn.setDeleted(1);
        clockInMapper.insertSelective(tClockIn);
        //添加积分
        TIntegral integral = new TIntegral();
        integral.setUserId(reqVo.getUserId());
        TIntegral resBean = integralMapper.selectOne(integral);
        if(DataUtil.isNullOrEmpty(resBean)){
            TIntegral newData = new TIntegral();
            newData.setId(IdBuilderUtil.getId());
            newData.setTotalScore(1L);
            newData.setCreateTime(System.currentTimeMillis());
            newData.setUserId(reqVo.getUserId());
            newData.setDeleted(1);
            integralMapper.insertSelective(newData);
        }else {
            resBean.setTotalScore(resBean.getTotalScore() + 1);
            integralMapper.updateByPrimaryKeySelective(resBean);
        }
        //添加打卡记录
        String currentTime = DataUtil.currentTime().split(" ", 0)[0];
        TRecord searchBean = new TRecord();
        searchBean.setRecordTime(currentTime);
        searchBean.setUserId(reqVo.getUserId());
        int count = recordMapper.selectCount(searchBean);
        if(count == 0){
            //插入打卡记录
            TRecord record = new TRecord();
            record.setCreateTime(System.currentTimeMillis());
            record.setId(IdBuilderUtil.getId());
            record.setUserId(reqVo.getUserId());
            record.setRecordTime(currentTime);
            recordMapper.insertSelective(record);
        }
        return ResultDTO.okOf(new ResIdVO(tClockIn.getId()));
    }

    @Override
    public ResultDTO<List<ResClockInListVO>> list(ReqClockInListVO reqVo) {
        ClockInListPO clockInListPO = BeanHelper.copyProperties(reqVo, ClockInListPO.class);
        //获取最近打卡记录数
        List<ResClockInListVO> resClockInList = clockInMapper.list(clockInListPO);
        if(CollectionUtils.isEmpty(resClockInList)){
            return ResultDTO.okOf(resClockInList);
        }
        //根据openId获取个人信息
        TUser searchBean = new TUser();
        searchBean.setId(reqVo.getUserId());
        List<TUser> userList = userMapper.select(searchBean);
        //获取分类名字
        resClockInList.forEach(bean->{
            TClassification classification = classificationMapper.selectByPrimaryKey(bean.getClassificationId());
            if(!CollectionUtils.isEmpty(userList)){
                bean.setName(userList.get(0).getName());
                bean.setUrl(userList.get(0).getUrl());
            }
            if(!DataUtil.isNullOrEmpty(classification)){
                bean.setClassificationName(classification.getName());
            }
        });
        return ResultDTO.okOf(resClockInList);
    }

    @Override
    public ResultDTO<ResPageVO<ResClockInListVO>> listOfPage(ReqPageVO vo) {
        Long beforeDay = getBeforeDay();
        PageHelper.startPage(vo.getCurrentPage(), vo.getPageSize());
        Example example = new Example(TClockIn.class);
        Example.Criteria criteria1 = example.createCriteria();
        criteria1.andGreaterThan("createTime", DataUtil.getBeforeDay());
        example.setOrderByClause("create_time asc");
        List<TClockIn> list =  clockInMapper.selectByExample(example);
        PageInfo<TClockIn> pageInfo = new PageInfo<>(list);
        //数据封装
        ResPageVO<ResClockInListVO> resPageVO = new ResPageVO<>();
        resPageVO.setTotal(pageInfo.getTotal());
        resPageVO.setCurrentPage(pageInfo.getPageNum());
        resPageVO.setPageSize(pageInfo.getSize());
        if(CollectionUtils.isEmpty(pageInfo.getList())){
            return ResultDTO.okOf(resPageVO);
        }
        resPageVO.setList(BeanHelper.copyWithCollection(pageInfo.getList(), ResClockInListVO.class));
        resPageVO.getList().forEach(bean->{
            TUser user = userMapper.selectByPrimaryKey(bean.getUserId());
            bean.setName(user.getName());
            bean.setUrl(user.getUrl());
        });
        return ResultDTO.okOf(resPageVO);
    }

    /**
     * 获取前一天时间的开始和结尾
     */
    public Long getBeforeDay(){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.add(Calendar.DATE, -1);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        return calendar.getTime().getTime();
    }
}
